package com.yonyou.isv.demo.openapi.api;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @description:
 * @author: nishch
 * @create: 2021-07-06
 **/
@Configuration
@RequiredArgsConstructor
public class BeansConfig {

    @Bean
    RestTemplate restTemplate(){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(60000);
        requestFactory.setReadTimeout(60000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        List<HttpMessageConverter<?>> httpMessageConverterList = restTemplate.getMessageConverters();
        // 设置 restTemplate StringHttpMessageConverter 编码方式
        for (HttpMessageConverter<?> httpMessageConverter : httpMessageConverterList) {
            if(httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName(StandardCharsets.UTF_8.toString()));
            }
        }
        restTemplate.setMessageConverters(httpMessageConverterList);
        return restTemplate;
    }

    @Bean
    public ApiBaseContext mddBaseContext() {
        return new ApiBaseContext();
    }

}